package com.wang.work;

import java.util.TimerTask;
import java.util.concurrent.locks.ReentrantLock;

public class TimerTaskTest extends TimerTask implements Runnable{
	public int sum = 200;//因为线程对象公用一个业务实现类所以不用static修饰
	public ReentrantLock lock = new ReentrantLock();
	public Thread person1 = new Thread(this,"苍苍");
	public Thread person2 = new Thread(this,"空空");
	@Override
	public void run() {
		changeState(person1);
		changeState(person2);
		while(sum > 0){
			rob();
		}
	}
	public void changeState(Thread thread){
		switch (thread.getState()) {
		case NEW:
			thread.start();
			break;
		case RUNNABLE:
			try {
				thread.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case WAITING :
			thread.notify();
			break;
		default:
			break;
		}
	}
	public TimerTaskTest() {
		super();
	}

	public void rob(){
		lock.lock();
		try {
			if(sum > 0)
				System.out.println(Thread.currentThread().getName()+"抢到第"+sum--+"豆子");
		}finally{
			lock.unlock();
		}
	}
}
